package com.erlin.common.config;

import com.erlin.common.client.*;
import feign.Feign;
import feign.Logger;
import feign.Request;
import feign.Retryer;
import feign.jackson.JacksonDecoder;
import feign.slf4j.Slf4jLogger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;

import static java.util.concurrent.TimeUnit.SECONDS;

@Configuration
public class FeignConfig {

    @Bean
    Logger.Level feignLoggerLevel() {
        //这里记录所有，根据实际情况选择合适的日志level
        return Logger.Level.FULL;
    }


    private <T> T builder(Class<T> tClass, String baseUrl) {
        return this.builder(tClass, baseUrl, 60, 60, 0, null);
    }

    private <T> T builder(Class<T> tClass, String baseUrl, long connectTimeoutSecond, long readTimeoutSecond, int maxAttempts, String token) {
        Feign.Builder feignBuilder = Feign.builder()
                .encoder(new FeignSpringFormEncoder())
                .decoder(new JacksonDecoder())
                .logLevel(Logger.Level.FULL)
                .logger(new Slf4jLogger(tClass))
                .options(new Request.Options(connectTimeoutSecond, SECONDS, readTimeoutSecond, SECONDS, true));

        // 设置重试次数
        if (maxAttempts <= 0) {
            feignBuilder.retryer(Retryer.NEVER_RETRY);
        } else {
            feignBuilder.retryer(new Retryer.Default(100, SECONDS.toMillis(1), maxAttempts));
        }

        // 设置token
        if (token != null && !token.isEmpty()) {
            feignBuilder.requestInterceptor(template -> template.header(HttpHeaders.AUTHORIZATION, token));
        }

        return feignBuilder.target(tClass, baseUrl);
    }

    @Bean
    public WxClient wxClient(@Value("${wx.url}") String baseUrl) {
        return this.builder(WxClient.class, baseUrl);
    }
}
